package grafi;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class GrafoMALagana<A extends Arco> extends GrafoMA<A> {

	public GrafoMALagana(int n) {
		super(n);
	}
	
	@Override 
	public Iterator<A> archi() {
		return new MioIteratore<A>();
	}
	
	@Override
	public Iterator<A> adiacenti(int v) {
		return new MioIteratore<A>(v);
	}
	
	protected class MioIteratore<A extends Arco> implements Iterator<A>{
		private int riga;
		private int col;
		private boolean nextRiga=false;
		
		
		public MioIteratore(){
			riga=0;
			col=0;
			nextRiga=true;
		}
		
		public MioIteratore(int riga){
			this.riga=riga;
			col=0;
			nextRiga=false;
		}

		@Override
		public boolean hasNext() {
			int colCorr=col;
			int rigaCorr=riga;
			if (colCorr>=M[0].length){					
				if (!nextRiga || rigaCorr==M.length-1){ //UltimaRiga
					return false;
				}
				rigaCorr++;
				colCorr=0;
			}			
			if (arco(rigaCorr,colCorr)){
				return true;
			}
			while (colCorr<M[0].length && !arco(rigaCorr,colCorr)){
				colCorr++;
				if (colCorr==M[0].length-1 && !arco(rigaCorr,colCorr)){					
					if (!nextRiga || rigaCorr==M.length-1){ //UltimaRiga
						return false;
					}
					rigaCorr++;
					colCorr=0;
				}
			}			
			return true;
		}

		@SuppressWarnings("unchecked")
		@Override
		public A next() {
			if (col>=M[0].length-1){
				if (!nextRiga || riga==M.length-1){ //UltimaRiga
					throw new NoSuchElementException();					
				}
				riga++;
				col=0;
			}
			while (col<M[0].length && !arco(riga,col)){
				col++;
				if (col==M[0].length-1 && !arco(riga,col)){
					if (!nextRiga || riga==M.length-1){ //UltimaRiga
						throw new NoSuchElementException();					
					}
					riga++;
					col=0;
				}
			}
			int colCorr=col;
			col++;
			return (A) M[riga][colCorr];
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException("Rimozione non consentita");
		}
		
	}

}
